package com.gzy.xuexiziliao.controller;

import com.gzy.xuexiziliao.common.result.Result;
import com.gzy.xuexiziliao.utils.AIUtil;
import com.gzy.xuexiziliao.utils.WebSocketUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Base64;

/**
 * AI控制器
 */
@RestController
@RequestMapping("/ai")
@RequiredArgsConstructor
public class AiController {

    private final AIUtil aiUtil;
    private static final String API_KEY = "da3b966862edc4a290ed2e24215f02ff";
    private static final String API_SECRET = "YzIzNTM4MTE2YTQwNjNmODk2OTJhYTZl";
    private static final String APP_ID = "e0a3b3a0";

    /**
     * 与AI进行对话
     * @param msg   用户输入的消息
     * @param model 使用的模型版本（例如："4.0Ultra"）
     * @return 统一响应结果
     */
    @GetMapping("/talk")
    public Result<String> chatWithAI(
            @RequestParam String msg,
            @RequestParam(defaultValue = "4.0Ultra") String model
    ) {
        try {
            String response = aiUtil.aiTalk(msg, model);
            return Result.success(response);
        } catch (Exception e) {
            return Result.error("AI服务请求失败: " + e.getMessage());
        }
    }




    @PostMapping("/imagechat")
    public ResponseEntity<String> analyzeImage(
            @RequestParam("image") MultipartFile file,
            @RequestParam("question") String question) { // 移除 api_key、api_secret、app_id 参数


        try {
            // 1. 生成鉴权参数（直接使用硬编码的 API_KEY 和 API_SECRET）
            String date = aiUtil.generateDate();
            String authorization = aiUtil.generateAuthorization(API_KEY, API_SECRET, date);

            // 2. 构造WebSocket请求URL
            String wsUrl = "wss://spark-api.cn-huabei-1.xf-yun.com/v2.1/image?" +
                    "authorization=" + URLEncoder.encode(authorization, "UTF-8") +
                    "&date=" + URLEncoder.encode(date, "UTF-8") +
                    "&host=spark-api.cn-huabei-1.xf-yun.com";

            // 3. 将图片转为Base64
            String base64Image = Base64.getEncoder().encodeToString(file.getBytes());

            // 4. 构造请求JSON（使用硬编码的 APP_ID）
            String requestJson = buildRequestJson(APP_ID, base64Image, question);

            // 5. 发送WebSocket请求
            String response = WebSocketUtil.sendWebSocketRequest(wsUrl, requestJson);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace(); // 输出堆栈信息到控制台
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error: " + e.getMessage() + "\nStack Trace: " + Arrays.toString(e.getStackTrace()));
        }
    }

    // 构造请求JSON（可提取到Service中）
    private String buildRequestJson(String appId, String imageBase64, String question) {
        return "{\n" +
                "  \"header\": {\n" +
                "    \"app_id\": \"" + appId + "\"\n" +
                "  },\n" +
                "  \"parameter\": {\n" +
                "    \"chat\": {\n" +
                "      \"domain\": \"imagev3\",\n" +
                "      \"temperature\": 0.5,\n" +
                "      \"top_k\": 4,\n" +
                "      \"max_tokens\": 2028\n" +
                "    }\n" +
                "  },\n" +
                "  \"payload\": {\n" +
                "    \"message\": {\n" +
                "      \"text\": [\n" +
                "        {\n" +
                "          \"role\": \"user\",\n" +
                "          \"content\": \"" + imageBase64 + "\",\n" +
                "          \"content_type\": \"image\"\n" +
                "        },\n" +
                "        {\n" +
                "          \"role\": \"user\",\n" +
                "          \"content\": \"" + question + "\",\n" +
                "          \"content_type\": \"text\"\n" +
                "        }\n" +
                "      ]\n" +
                "    }\n" +
                "  }\n" +
                "}";
    }
}



